﻿using Microsoft.AspNetCore.Mvc.Filters;

namespace EasyDDD.Host.WebAPI
{
    /// <summary>
    /// 根据User的ClaimTypes.Role判断权限
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class AuthorizeClaimAttribute : Attribute, IAuthorizationFilter
    {
        public string ClaimType { get; set; }
        public string ClaimValue { get; set; }

        public AuthorizeClaimAttribute(string claimType, string claimValue)
        {
            ClaimType = claimType;
            ClaimValue = claimValue;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (context.HttpContext.User.Identity?.Name == "superadmin")
            {
                return;
            }
            if (context.HttpContext.User.IsInRole("superadmin"))
            {
                return;
            }
            if (context.HttpContext.User.HasClaim(ClaimTypes.Role, "superadmin"))
            {
                return;
            }
            if (!context.HttpContext.User.HasClaim(ClaimType, ClaimValue))
            {
                throw new Exception("您没有该权限！");
            }

        }
    }
}